<?php
class InventoryTable extends Doctrine_Table
{
    public function retrieveActiveBook(Doctrine_Query $q)
    {
        return $this->addActiveBooksQuery($q)->fetchOne();
    }
    public function getActiveBooks(Doctrine_Query $q = null)
    {
        return $this->addActiveBooksQuery($q)->execute();
    }
    public function countActiveBooks(Doctrine_Query $q = null)
    {
        return $this->addActiveBooksQuery($q)->count();
    }
    public function addActiveBooksQuery(Doctrine_Query $q = null)
    {
        if (is_null($q))
        {
            $q = Doctrine_Query::create()->from('Inventory a');
        }
        $q->leftJoin('a.Book b')
            ->andWhere('a.expires_at > ?', date('Y-m-d H:i:s', time()))
            ->andWhere('a.state_id > ?', 1)
            ->addOrderBy('a.price ASC')
            ->addOrderBy('b.title ASC');
        return $q;
    }
    static public function getLuceneIndex()
    {
        ProjectConfiguration::registerZend();
        if (file_exists($index = self::getLuceneIndexFile()))
        {
            return Zend_Search_Lucene::open($index);
        }
        else
        {
            return Zend_Search_Lucene::create($index);
        }
    }
    static public function getLuceneIndexFile()
    {
        return sfConfig::get('sf_data_dir') . '/inventory.' . sfConfig::get('sf_environment') . '.index';
    }
    
    public function getForLuceneQuery($query)
    {
        $hits = $this->getLuceneIndex()->find($query);
        $pks = array();
        foreach ($hits as $hit)
        {
            $pks[] = $hit->pk;
        }
        if (empty($pks))
        {
            return array();
        }
        $q = $this->createQuery('a')->whereIn('a.id', $pks)->limit(20);
        $q = $this->addActiveBooksQuery($q);
        return $q->execute();
    }
}